import 'package:flutter/material.dart';
import '../../models/serach_info_model.dart';
import '../../components/quantity_selector.dart';
import 'package:ninetyfour/l10n/app_localizations.dart';
import '../../models/yh_info_model.dart';
import '../../manger/user_manger.dart';
import '../../login/controller/login_view.dart';

class ProductBottomView extends StatefulWidget {
  final ReListModel? selectedModel;
  final List<CouponListModel>? couponInfoModel;
  final int productNum;
  final ValueChanged<int>? onProductNumChanged;
  final bool isDiscount; // 是否是折扣产品
  final VoidCallback? onTap;
  final bool isSelect;
  const ProductBottomView({
    super.key,
    required this.selectedModel,
    required this.couponInfoModel,
    required this.productNum,
    required this.isDiscount,
    this.onProductNumChanged,
    this.onTap,
    required this.isSelect
  });

  @override
  State<ProductBottomView> createState() => _ProductBottomViewState();
}

class CouponResult {
  final Widget widget;
  final bool haveDiscount;
  final double endDiscount;
  CouponResult({
    required this.widget,
    required this.haveDiscount,
    required this.endDiscount,
  });
}

class _ProductBottomViewState extends State<ProductBottomView> {
  double _endDiscount = 0.0;
  DateTime? lastClickTime;

  bool checkClickInterval() {
    final now = DateTime.now();
    if (lastClickTime != null &&
        now.difference(lastClickTime!).inMilliseconds < 2000) {
      return false;
    }
    lastClickTime = now;
    return true;
  }

  String formatAmount(double value) {
    final rounded = (value * 100).round() / 100.0;
    if (rounded == rounded.roundToDouble()) {
      return rounded.toStringAsFixed(0);
    } else if ((rounded * 10).roundToDouble() == rounded * 10) {
      return rounded.toStringAsFixed(1);
    } else {
      return rounded.toStringAsFixed(2);
    }
  }

  String _getFinalPrice() {
    if (!widget.isDiscount) {
      _endDiscount = 0.0;
    }
    final price = (double.tryParse(widget.selectedModel?.priceFee.toString() ?? '0') ?? 0.0) *
            widget.productNum -
        _endDiscount;
    return "${widget.selectedModel?.symbol ?? ""}${(price < 0 ? 0 : price).toStringAsFixed(2)}";
  }

  CouponResult buildCouponResult(
      double amount, List<CouponListModel> coupons) {
    var totalAmount = amount * widget.productNum;

    if (coupons.isEmpty && !widget.isDiscount) {
      return CouponResult(widget: Container(), haveDiscount: false, endDiscount: 0.0);
    }

    // 处理 type=1 的优惠券
    var processedCoupons = coupons.map((coupon) {
      if (coupon.type == "1") {
        final rawDiscount = (1 - coupon.parvalue) * totalAmount;
        final discountAmount = (coupon.max > 0)
            ? rawDiscount.clamp(0, coupon.max).toDouble()
            : rawDiscount.toDouble();
        return coupon.copyWith(parvalue: discountAmount);
      }
      return coupon;
    }).toList();

    // 筛选可用的优惠券
    final validCoupons =
        processedCoupons.where((c) => c.cill <= totalAmount).toList();

    if (validCoupons.isEmpty) {
      if (coupons.isNotEmpty) {
        final minCillCoupon =
            coupons.reduce((a, b) => a.cill < b.cill ? a : b);
        final remaining = minCillCoupon.cill - totalAmount;
        return CouponResult(
          haveDiscount: false,
          endDiscount: 0.0,
          widget: RichText(
            text: TextSpan(children: [
              TextSpan(
                text: isChineseLocale() ? '还差' : 'Need ',
                style: const TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
              ),
              TextSpan(
                text: '${minCillCoupon.symbol}${remaining.toStringAsFixed(2)}',
                style: const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
              ),
              TextSpan(
                text: isChineseLocale() ? '可用劵抵扣' : ' Save ',
                style: const TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
              ),
              TextSpan(
                text: '${minCillCoupon.symbol}${minCillCoupon.parvalue}',
                style: const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
              ),
            ]),
          ),
        );
      } else {
        return CouponResult(widget: Container(), haveDiscount: false, endDiscount: 0.0);
      }
    }

    // 有效优惠券，取最大优惠
    final maxCoupon =
        validCoupons.reduce((a, b) => a.parvalue > b.parvalue ? a : b);
    final nextCoupons = processedCoupons
        .where((c) => c.cill > totalAmount && c.parvalue > maxCoupon.parvalue)
        .toList();

    if (nextCoupons.isEmpty) {
      return CouponResult(
        haveDiscount: true,
        endDiscount: maxCoupon.parvalue,
        widget: RichText(
          text: TextSpan(children: [
            TextSpan(
              text: isChineseLocale() ? '可用劵抵扣' : 'Save ',
              style: const TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
            ),
            TextSpan(
              text:
                  '${maxCoupon.symbol}${maxCoupon.parvalue.toStringAsFixed(2)}',
              style: const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
            ),
          ]),
        ),
      );
    }

    final minNextCoupon =
        nextCoupons.reduce((a, b) => a.cill < b.cill ? a : b);
    final remaining = minNextCoupon.cill - totalAmount;

    return CouponResult(
      haveDiscount: true,
      endDiscount: maxCoupon.parvalue,
      widget: isChineseLocale()
          ? RichText(
              text: TextSpan(children: [
                TextSpan(
                  text: AppLocalizations.of(context)!.discount1,
                  style:
                      const TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
                ),
                TextSpan(
                  text: '${maxCoupon.symbol}${formatAmount(maxCoupon.parvalue)}',
                  style:
                      const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
                ),
                TextSpan(
                  text: AppLocalizations.of(context)!.discount2,
                  style:
                      const TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
                ),
                TextSpan(
                  text: '${maxCoupon.symbol}${formatAmount(remaining)}',
                  style:
                      const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
                ),
                TextSpan(
                  text: AppLocalizations.of(context)!.discount3,
                  style:
                      const TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
                ),
                TextSpan(
                  text:
                      '${minNextCoupon.symbol}${formatAmount(minNextCoupon.parvalue)}',
                  style:
                      const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
                ),
              ]),
            )
          : RichText(
              text: TextSpan(children: [
                const TextSpan(
                  text: "Save ",
                  style: TextStyle(color: Color(0xFF2A2A2A), fontSize: 13),
                ),
                TextSpan(
                  text: '${maxCoupon.symbol}${formatAmount(maxCoupon.parvalue)}',
                  style:
                      const TextStyle(color: Color(0xFFF61F03), fontSize: 13),
                ),
              ]),
            ),
    );
  }

  String _buildPriceText(bool haveDiscount) {
    if (isChineseLocale()) {
      if (UserInfos.shared.token.isNotEmpty) {
        if (haveDiscount) {
          return '券后价';
        } else {
          if (UserInfos.shared.userModel?.level?.appLevelName.isNotEmpty ?? false) {
            return '${UserInfos.shared.userModel?.level?.appLevelName}价';
          } else {
            return 'vip1价';
          }
        }
      } else {
        return widget.isDiscount ? '新人价' : '';
      }
    } else {
      if (haveDiscount) {
        return 'Discounted';
      } else {
        if (UserInfos.shared.userModel?.level?.appLevelName.isNotEmpty ?? false) {
          return '${UserInfos.shared.userModel?.level?.appLevelName}';
        } else {
          return 'vip1';
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final couponResult = buildCouponResult(
      double.tryParse(widget.selectedModel?.priceFee.toString() ?? '') ?? 0.0,
      widget.couponInfoModel ?? [],
    );
    _endDiscount = couponResult.endDiscount;

    return SafeArea(
      top: false,
      bottom: false,
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(top: BorderSide(color: Colors.grey.shade200)),
        ),
        padding: const EdgeInsets.only(left: 20, right: 15, bottom: 20, top: 10),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (UserInfos.shared.token.isNotEmpty && isChineseLocale() && widget.isDiscount)
              Container(
                decoration: BoxDecoration(
                  color: const Color(0xFFFDEAE9),
                  borderRadius: BorderRadius.circular(8),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Image.asset('assets/images/折扣.png', width: 16, height: 16),
                    couponResult.widget,
                  ],
                ),
              ),
            const SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            _getFinalPrice(),
                            style: const TextStyle(
                              color: Color(0xFFF61F03),
                              fontSize: 19,
                              fontWeight: FontWeight.w900,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 8),
                            child: Container(
                              height: 20,
                              padding: const EdgeInsets.symmetric(horizontal: 6),
                              decoration: BoxDecoration(
                                color: UserInfos.shared.token.isNotEmpty
                                    ? (couponResult.haveDiscount
                                        ? const Color(0xFFF61F03)
                                        : const Color.fromARGB(255, 240, 188, 125))
                                    : (couponResult.haveDiscount
                                        ? const Color(0xFFF61F03)
                                        : Colors.transparent),
                                borderRadius: const BorderRadius.only(
                                  bottomLeft: Radius.circular(10),
                                  topRight: Radius.circular(10),
                                ),
                              ),
                              child: Center(
                                child: Text(
                                  _buildPriceText(couponResult.haveDiscount),
                                  style: TextStyle(
                                    color: couponResult.haveDiscount
                                        ? Colors.white
                                        : const Color(0xFF333333),
                                    fontSize: 11,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          Text(
                            isChineseLocale()
                                ? '${AppLocalizations.of(context)!.marketPrice}${widget.selectedModel?.symbol}${((double.tryParse(widget.selectedModel?.marketPrice.toString() ?? '0') ?? 0.0) * widget.productNum).toStringAsFixed(2)}'
                                : '${widget.selectedModel?.symbol}${((double.tryParse(widget.selectedModel?.marketPrice.toString() ?? '0') ?? 0.0) * widget.productNum).toStringAsFixed(2)}',
                            style: const TextStyle(
                              color: Color(0xFF7D7D7D),
                              fontSize: 12,
                              decoration: TextDecoration.lineThrough,
                              decorationColor: Color(0xFF7D7D7D),
                            ),
                          ),
                          const SizedBox(width: 6),
                          if (!isChineseLocale() && widget.isDiscount)
                            Container(
                              decoration: BoxDecoration(
                                color: const Color(0xFFFDEAE9),
                                borderRadius: BorderRadius.circular(8),
                              ),
                              padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Image.asset('assets/images/折扣.png', width: 16, height: 16),
                                  couponResult.widget,
                                ],
                              ),
                            ),
                        ],
                      ),
                    ],
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 0),
                  child: QuantitySelector(
                    onChanged: (value) {
                      widget.onProductNumChanged?.call(value);
                    },
                  ),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Center(
              child: SizedBox(
                width: MediaQuery.of(context).size.width - 100,
                height: 50,
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.transparent,
                    shadowColor: Colors.transparent,
                    padding: EdgeInsets.zero,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(19),
                    ),
                  ),
                  onPressed: () {
                    if (!checkClickInterval()) return;
                    if (UserInfos.shared.token.isNotEmpty) {
                      if (!widget.isSelect) {
                        widget.onTap?.call();
                      }
                    } else {
                      if (!widget.isSelect) {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => const LoginView()),
                        );
                      }
                    }
                  },
                  child: Container(
                    height: 38,
                    decoration: widget.isSelect
                        ? BoxDecoration(
                            color: const Color(0xFFC1C1C1),
                            borderRadius: BorderRadius.circular(19),
                          )
                        : BoxDecoration(
                            gradient: const LinearGradient(
                              colors: [Color(0xFF5F60EF), Color(0xFF8A9CFF)],
                              begin: Alignment.centerLeft,
                              end: Alignment.centerRight,
                            ),
                            borderRadius: BorderRadius.circular(19),
                            boxShadow: const [
                              BoxShadow(
                                color: Color(0x665D5FEE),
                                blurRadius: 10.3,
                                offset: Offset(0, 10.3),
                              ),
                            ],
                          ),
                    alignment: Alignment.center,
                    child: Text(
                      widget.isSelect ? AppLocalizations.of(context)!.soldout : AppLocalizations.of(context)!.buyNow,
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
